<template>
  <!-- 筛选区 -->
  <div class="sub-filter">
    <div class="item" v-for="item in list" :key="item.id">
      <div class="head">{{ item.name }}</div>
      <div class="body">
        <a href="javascript:;"
        @click="getFilterParams(item, {})"
         :class="{ active: item.activeName === undefined }"
        >全部</a>
        <a href="javascript:;"
         v-for="item2 in item.properties"
         :key="item2.id"
         :class="{ active: item.activeName === item2.name }"
        @click="getFilterParams(item, item2)">
          {{item2.name}}</a>
      </div>
    </div>
  </div>
</template>

<script>
import { inject, computed, reactive } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    // 获取父组件上提供的数据
    const subFilter = inject('subFilter')
    // console.log(subFilter);
    const reqParams = inject('reqParams')

    // console.log(reqParams)
    const list = computed(() => {
      return [
        reactive({ id: 'brand', name: '品牌', properties: subFilter.value.brands }),
        ...subFilter.value.saleProperties
      ]
    })
    // console.log('11', list)
    // 获取筛选参数 [{ groupName: 属性组名称, propertyName: 属性名称 }]
    const getFilterParams = (theItem, theItem2) => {
      // console.log(theItem, theItem2)
      const groupName = theItem.name
      const propertyName = theItem2.name
      // 获取筛选参数有两种情况：
      //  情况1. 获取品牌 id
      if (groupName === '品牌') {
        reqParams.brandId = theItem2.id
        return
      }
      // 👍 给一级对象添加收集到的数据，用于筛选区高亮
      theItem.activeName = propertyName
      // 单个属性
      const attr = { groupName, propertyName }
      // 如果属性已经存在就修改属性的值，如果是不存在则追加
      const obj = reqParams.attrs.find(item => item.groupName === groupName)
      if (obj) {
        // 存在，修改
        obj.propertyName = propertyName
      } else {
        // 不存在：追加
        reqParams.attrs.push(attr)
      }
    }

    return { list, getFilterParams }
  }
}
</script>

<style scoped lang="less">
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    line-height: 40px;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        display: inline-block;
        &.active,
        &:hover {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>
